<?php

namespace mpend\models;

use Yii;
use yii\data\ActiveDataProvider;

/**
 * ActivitiesSearch represents the model behind the search form of `common\models\original\Activities`.
 */
class SearchModel extends \yii\base\Model {

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params = []) {
        $modelClass = static::instance()->searchModel;
        $query = $modelClass::find()->where([
            'status' => $modelClass::STATUS_ACTIVE,
            'deleted_at' => 0,
        ]);

        $query->with('user');

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 1,
            ],
        ]);

        if ($this->load($params) && $this->validate()) {
            $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'scope', $this->scope]);
            if ($this->start_at == 0 && $this->start_at != '') { //活动未开始
                $query->andWhere(['>', 'start_at', $now_time]);
            }
            if ($this->start_at == 1) { //活动进行中
                $query->andWhere(['<=', 'start_at', $now_time]);
                $query->andWhere(['>', 'end_at', $now_time]);
            }
            if ($this->start_at == 2) { //活动结束
                $query->andWhere(['<=', 'end_at', $now_time]);
            }
            if (isset($params['union'])) {
                $query->andFilterWhere([
                    'union_id' => $params['union'],
                ]);
            } else {
                $query->andFilterWhere([
                    'type' => $this->type,
                ]);
            }
            // grid filtering conditions
            $query->orderBy('created_at desc');
        }

        Yii::$app->db->cache(function($db) use($dataProvider) {
            $dataProvider->prepare();
        }, 60);

        return $dataProvider;
    }

}
